#!/bin/bash
# AIOT智能学习桌项目 - 开发环境安装脚本

echo "=========================================="
echo "AIOT智能学习桌项目开发环境安装"
echo "=========================================="

# 检查操作系统
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    echo "检测到Linux系统"
    PACKAGE_MANAGER="apt"
elif [[ "$OSTYPE" == "darwin"* ]]; then
    echo "检测到macOS系统"
    PACKAGE_MANAGER="brew"
else
    echo "不支持的操作系统: $OSTYPE"
    exit 1
fi

# 更新包管理器
echo "更新包管理器..."
if [ "$PACKAGE_MANAGER" = "apt" ]; then
    sudo apt update
elif [ "$PACKAGE_MANAGER" = "brew" ]; then
    brew update
fi

# 安装基础开发工具
echo "安装基础开发工具..."
if [ "$PACKAGE_MANAGER" = "apt" ]; then
    sudo apt install -y build-essential git cmake
elif [ "$PACKAGE_MANAGER" = "brew" ]; then
    brew install git cmake
fi

# 安装ARM交叉编译工具链
echo "安装ARM交叉编译工具链..."
if [ "$PACKAGE_MANAGER" = "apt" ]; then
    sudo apt install -y gcc-arm-none-eabi gdb-arm-none-eabi
elif [ "$PACKAGE_MANAGER" = "brew" ]; then
    brew install --cask gcc-arm-embedded
fi

# 安装OpenOCD调试器
echo "安装OpenOCD调试器..."
if [ "$PACKAGE_MANAGER" = "apt" ]; then
    sudo apt install -y openocd
elif [ "$PACKAGE_MANAGER" = "brew" ]; then
    brew install openocd
fi

# 安装Python开发环境
echo "安装Python开发环境..."
if [ "$PACKAGE_MANAGER" = "apt" ]; then
    sudo apt install -y python3 python3-pip python3-venv
elif [ "$PACKAGE_MANAGER" = "brew" ]; then
    brew install python3
fi

# 创建Python虚拟环境
echo "创建Python虚拟环境..."
python3 -m venv .venv
source .venv/bin/activate

# 安装Python依赖
echo "安装Python依赖..."
pip install --upgrade pip
pip install -r requirements.txt

# 安装串口工具
echo "安装串口工具..."
if [ "$PACKAGE_MANAGER" = "apt" ]; then
    sudo apt install -y minicom screen
    # 添加用户到dialout组
    sudo usermod -a -G dialout $USER
elif [ "$PACKAGE_MANAGER" = "brew" ]; then
    brew install minicom screen
fi

# 安装代码编辑器插件推荐
echo "推荐的开发工具:"
echo "1. Visual Studio Code + C/C++ Extension"
echo "2. CLion (JetBrains)"
echo "3. Eclipse CDT"

# 创建必要的目录
echo "创建项目目录结构..."
mkdir -p build
mkdir -p logs
mkdir -p data
mkdir -p user_profiles

# 设置权限
chmod +x *.sh

# 验证安装
echo "验证安装..."
echo "检查ARM工具链:"
arm-none-eabi-gcc --version

echo "检查OpenOCD:"
openocd --version

echo "检查Python:"
python3 --version

echo "检查pip包:"
pip list | grep -E "(opencv|mediapipe|numpy)"

echo "=========================================="
echo "开发环境安装完成!"
echo "=========================================="
echo ""
echo "下一步操作:"
echo "1. 连接EBP3901开发板"
echo "2. 配置串口权限: sudo usermod -a -G dialout \$USER"
echo "3. 重新登录以应用权限更改"
echo "4. 运行: make help 查看可用命令"
echo "5. 编译项目: make all"
echo "6. 烧录程序: make flash"
echo ""
echo "Python仿真环境:"
echo "1. 激活虚拟环境: source .venv/bin/activate"
echo "2. 运行仿真: python run.py --mode simulator"
echo "3. 运行语音版: python run.py --mode voice"
echo ""
echo "注意事项:"
echo "- 确保EBP3901开发板驱动已正确安装"
echo "- 检查USB连接和串口权限"
echo "- 根据实际硬件调整GPIO引脚配置"